﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace OmniKits.Core
{
    public abstract class SimpleJob : ICanStart, ICanWait
    {
        internal Thread _Thread = null;

        protected abstract void Main();
        public virtual bool Start()
        {
            if (_Thread != null)
                return false;

            try
            {
                _Thread = new Thread(() =>
                {
                    try
                    {
                        Main();
                    }
                    finally
                    {
                        _Thread = null;
                    }
                });
                _Thread.Start();
            }
            catch
            {
                _Thread = null;
            }
            return true;
        }

        public virtual bool Wait()
        {
            var thread = _Thread;
            if (thread == null)
                return false;

            try
            {
                thread.Join();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
    public abstract class SimpleJobCanStop : SimpleJob, ICanStop
    {
        public virtual bool Stop()
        {
            var thread = _Thread;
            if (thread == null)
                return false;

            _Thread = null;
            thread.Abort();
            return true;
        }
    }
}
